Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
What "Init only setters" provides and what is the difference to the readonly one in C#

I can define a class like below:

public class MyClass
{
  public int Id { get; }
  public MyClass(int id) => Id = id;
}

And I have to define the Id from the constructor and it will be read-only.

But if I want to use Init only setters in the C# 9.0, what does it and how can I use it?

public class MyClass
{
  public int Id { get; init; }
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

In a nutshell:

var obj = new MyClass
{
    Id = 42 // totally fine
};

obj.Id = 43; // not OK, we're not initializing

Trivial in this case and not much different to using a constructor parameter, but useful in some more complex scenarios where you don't want 200 constructor parameters, but you do want it to be outwardly immutable once constructed.

over 4 years ago · Santiago Trujillo Relatório

0

Init only setters provide consistent syntax to initialize members of an object. Property initializers make it clear which value is setting which property. The downside is that those properties must be settable.

With that, you don't need to provide the value at the beginning and the constructor and you can do it afterward:

var myClass = new MyClass 
{ 
   Id = 10 
}

and it will be sealed and you cannot change it anymore.

myClass.Id = 43; // not allowed

read more info

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda